import 'dart:convert';


import 'package:audioplayers/audioplayers.dart';
import 'package:get/get.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/global_data.dart';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';
import 'state.dart';
import 'dart:math';

class RandComLogic extends GetxController {
  final RandComState state = RandComState();
  var cachekey = '';
  final player = AudioPlayer();
  @override
  void onInit() {
    super.onInit();
    cachekey=state.randComArgs.value.cachekey;

    initCache();
    state.funStart=() async {
      await generateRandomNumbersStart();
    };

  }

  // 初始化缓存
  Future<void> initCache() async {
    final prefs = await SharedPreferences.getInstance();
    state.min.value = prefs.getInt(cachekey+'min') ?? 0;
    state.max.value = prefs.getInt(cachekey+'max') ?? 100;
    state.count.value = prefs.getInt(cachekey+'count') ?? 1;
    state.randomNumbersSum.value = prefs.getInt(cachekey+'randomNumbersSum') ?? 0;
    state.isRepeatable.value = prefs.getBool(cachekey+'isRepeatable') ?? false;
    // 新增初始化缓存
    state.scrollTime.value = prefs.getInt(cachekey+'scrollTime') ?? 3;
    state.isManualStop.value = prefs.getBool('isManualStop') ?? true;

    //这两个为通用设置
    state.isSoundEnabled.value = prefs.getBool('isSoundEnabled') ?? true;
    state.isVibrationEnabled.value = prefs.getBool('isVibrationEnabled') ?? true;

    state.isShowSum.value = prefs.getBool(cachekey+'isShowSum') ?? false;
    state.isadd0.value = prefs.getBool(cachekey+'isadd0') ?? false;

    // 读取随机数列表
    final List<String>? stringNumbers = prefs.getStringList(cachekey+'randomNumbers');
    if (stringNumbers != null) {
      state.randomNumbers.value = stringNumbers;
    } else {
      state.randomNumbers.value = [];
    }
  }

  void setSave(int min, int max, int count, bool isRepeatable, int scrollTime, bool isManualStop, bool isSoundEnabled, bool isVibrationEnabled) {
    if (min > max) {
      int temp = min;
      min = max;
      max = temp;
    }
    if (count < 1) {
      count = 1;
    }
    if (count > 10) {
      count = 10;
    }
    if (min < 0) {
      min = 0;
    }
    if (max > 99999) {
      max = 99999;
    }
    // 限制滚动时间范围
    scrollTime = scrollTime.clamp(1, 9);
    state.min.value = min;
    state.max.value = max;
    state.count.value = count;
    state.isRepeatable.value = isRepeatable;
    state.scrollTime.value = scrollTime;
    state.isManualStop.value = isManualStop;
    state.isSoundEnabled.value = isSoundEnabled;
    state.isVibrationEnabled.value = isVibrationEnabled;
    //state.randomNumbers.value = [];
    saveToCache();
  }

  void setRepeatable(bool isRepeatable) {
    state.isRepeatable.value = isRepeatable;
  }

  // 保存到缓存
  Future<void> saveToCache() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt(cachekey+'min', state.min.value);
    prefs.setInt(cachekey+'max', state.max.value);
    prefs.setInt(cachekey+'count', state.count.value);
    prefs.setBool(cachekey+'isRepeatable', state.isRepeatable.value);
    // 新增保存到缓存
    prefs.setInt(cachekey+'scrollTime', state.scrollTime.value);
    prefs.setBool('isManualStop', state.isManualStop.value);


    prefs.setBool('isSoundEnabled', state.isSoundEnabled.value);
    prefs.setBool('isVibrationEnabled', state.isVibrationEnabled.value);

    prefs.setBool(cachekey+'isShowSum', state.isShowSum.value);
    prefs.setBool(cachekey+'isadd0', state.isadd0.value);
  }

  void payRunMp3({type="start"}) async {
    if (state.isSoundEnabled.value) {
      if (type=="start") {
       commonFuc.playMp3(path: globalData.soundPath);
      } else {
        commonFuc.playMp3(path: globalData.soundSuccessPath);
      }
    }
  }


  // 保存到缓存
  Future<void> saveToCachehistoryNumbers() async {
    // 立即停止播放音乐
     payRunMp3(type: "stop");
    final prefs = await SharedPreferences.getInstance();
    final numbersAsStrings = state.randomNumbers.value.map((number) => number.toString()).toList();
    prefs.setStringList(cachekey+'randomNumbers', numbersAsStrings);
    prefs.setInt(cachekey+'randomNumbersSum', state.randomNumbersSum.value);

    // 保存历史记录
    final String? historyJson = prefs.getString(cachekey+'historyNumbers');
    //print('historyJson: $historyJson');
    if (historyJson != null) {
      try {
        state.historyNumbers.value = jsonDecode(historyJson);

      } catch (e) {
        print('解析历史记录失败: $e');
      }
    }

    if (state.historyNumbers.length>=200) {
      state.historyNumbers.removeAt(0);
    }
    state.historyNumbers.add({
      "list": state.randomNumbers.value.join(','),
      "sum": state.randomNumbersSum.value,
      "isshowsum": state.isShowSum.value,
      "time": commonFuc.getNowTimeYmdHis()
    });
    //print('historyNumbers: ${state.historyNumbers.value}');
    // 保存历史记录
    prefs.setString(cachekey+'historyNumbers', jsonEncode(state.historyNumbers.value));
  }


  Future<void> runComFunStart() async {

    state.isRun.value = 1;
    // 这个函数可以根据实际情况自定义。
   await  state.funStart?.call();

    state.isRun.value = 2;

    // 震动提示
    if (state.isVibrationEnabled.value && await Vibration.hasVibrator() ?? false) {
      Vibration.vibrate(duration: 50);
    }
  }


  void generateRandomNumbersStop(int isrun,{Function? funStop}) async {
    state.isRun.value = isrun;
    update();
    await Future.delayed(const Duration(milliseconds: 200));
    funStop?.call();
  }
  // 每 500 毫秒调用一次 generateRandomNumbersRun 方法，共调用 3 次
  Future<void> generateRandomNumbersStart() async {
    int scrollTime = state.scrollTime.value.clamp(1, 9);
    int loopCount = scrollTime * 10;
    if (state.isManualStop.value) {
      loopCount = 10000;
    }
    payRunMp3();
    for (int i = 0; i < loopCount; i++) {
      if (state.isRun.value != 1) {
        generateRandomNumbersRunOne(isSaveCache: true);
        break;
      }
      // print(i);
      await Future.delayed(const Duration(milliseconds: 100));
      generateRandomNumbersRunOne(isSaveCache: loopCount==i+1);
      // 声音提示
    }
  }



  void generateRandomNumbersRunOne({bool isSaveCache = false}) {
    try {
      // 参数校验
      if (state.min.value > state.max.value) {
        state.min.value=1;
      }
      if (state.count.value <= 0) {
        state.count.value=1;
      }
      final random = Random();
      final List<String> numbers = [];
      var count = state.count.value;
      final bool isRepeatable = state.isRepeatable.value;
      final numbersdefs =state.randComArgs.value.list.split(",");
      // 生成随机数逻辑
      if (isRepeatable) {
        // 可重复模式
        numbers.addAll(
          List.generate(
            count,
                (_) => numbersdefs[random.nextInt(numbersdefs.length)],
          ),
        );
      } else {
        // 不可重复模式
        if (count > numbersdefs.length) {
          count = numbersdefs.length;
        }

        final shuffled = List<String>.from(numbersdefs)..shuffle(random);
        numbers.addAll(shuffled.take(count));
      }

      // 更新状态
      state.randomNumbers.value = numbers;
      state.randomNumbersSum.value = numbers.isNotEmpty
          ? commonFuc.sumNumbers(numbers)
          : 0;

      // 缓存处理
      if (isSaveCache) {
        state.funStop?.call();
        saveToCachehistoryNumbers();
      }

      update();
    } catch (e) {
      // 错误处理
     // debugPrint('生成随机数出错: $e');
      // 可以根据需要在这里添加错误恢复或状态重置逻辑
      rethrow; // 或者处理错误后继续
    }
  }
}
